package config

import (
	"encoding/json"
	"github.com/dgrijalva/jwt-go"
	"time"
)

type User struct {
	Id         int    `json:"id"`
	Nickname   string `orm:"column(nickname)" json:"nickname"`
	Tel        string `orm:"column(tel)" json:"tel"`
	Headimg    string `orm:"column(headimg)" json:"headimg"`
	Name       string `orm:"column(name)" json:"name"`
	CreateTime int    `orm:"column(create_time)" json:"create_time"` //创建token的时间
}

// GetExpireTime 获取token过期时间
func GetExpireTime() time.Duration {
	m := ExpireTime * 60 //获取过期分钟数
	expireTime := time.Duration(m) * time.Minute

	return expireTime
}

// CreateToken  生成用户token
func CreateToken(id int, nickname string, mobile string, avatar string, name string) (string, error) {

	timeEd := time.Now().Unix()
	var system User
	system.Id = id
	system.Nickname = nickname
	system.Tel = mobile
	system.Headimg = avatar
	system.Name = name
	system.CreateTime = int(timeEd)

	signingKey := []byte(SignKey)

	str, err := json.Marshal(system)
	if err != nil {
		return "", err
	}
	expireTime := GetExpireTime()

	claims := &jwt.StandardClaims{
		// 过期时间
		ExpiresAt: time.Now().Add(expireTime).Unix(),
		// 发行者
		Issuer: string(str),
	}

	// 创建JWT令牌
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

	// 签名令牌
	signedToken, err := token.SignedString(signingKey)

	return signedToken, err
}

// TokenDecrypt 解析Token
func TokenDecrypt(token string) (User, error) {
	var user User
	// 使用你在设置JWT中间件时定义的签名密钥来解密和解码token
	tokens, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
		// 这里的[]byte("your_signing_key")应该是你的签名密钥
		return []byte(SignKey), nil
	})

	if err != nil {
		return user, err
	}
	claims, _ := tokens.Claims.(jwt.MapClaims)

	var iss = claims["iss"]
	iss1 := iss.(string)

	err1 := json.Unmarshal([]byte(iss1), &user)
	if err1 != nil {
		return user, err1
	}

	return user, nil
}

// GetTokenExpireTime 获取token过期时间
func GetTokenExpireTime() time.Duration {
	m := ExpireTime * 60 //获取过期分钟数
	expireTime := time.Duration(m) * time.Minute

	return expireTime
}
